<template>
  <div>
    <common-head title="购物车" />
    <div class="items">
      <div v-if='showCart'>
        <div class="top">
          <van-swipe-cell v-for="(item,index) in items" :key="item.id">
          <div class="item">
            <van-checkbox v-model="item.checked" @click='changeChecked' />
            <van-card
              :num="item.num"
              :price="item.minPrice"
              :title="item.tags"
              :thumb="item.pic"
            >
              <template #footer>
                <van-stepper v-model="item.num" @change='changeNum'/>
              </template>
            </van-card>
          </div>
          <template #right>
            <van-button
              square
              text="删除"
              type="danger"
              class="delete-button"
              @click='deleteItem(index)'
            />
          </template>
        </van-swipe-cell>
        </div>
        <div class="bottom">
          <van-submit-bar
          :price="totalPrice * 100"
          button-text="提交订单"
          @submit="onSubmit"
        >
          <van-checkbox v-model="allChecked">全选</van-checkbox>
        </van-submit-bar>
        </div>
      </div>

      <div v-if="!showCart" class="kongkong">
        <img src="@/assets/imgs/kongkong.jpg" alt="" style="width: 100%" />
        <p>购物车还是空空的呢~~</p>
        <div class="guang" @click="enterDetail">逛一逛</div>
      </div>
    </div>

    <my-tabbar></my-tabbar>
  </div>
</template>

<script>
import MyTabbar from '@components/MyTabbar'
import CommonHead from '@components/CommonHead'
import { mapState, mapMutations } from 'vuex'
import { Dialog } from 'vant'
export default {
  namespaced: true,
  data () {
    return {
      showCart: true
    }
  },
  components: {
    MyTabbar,
    CommonHead
  },
  created () {
    this.checkedPrice()
    this.showKong()
  },
  methods: {
    onSubmit () {
      const checkedItems = this.items.filter(el => el.checked)
      const total = this.totalPrice
      // 将选中的商品以及总价格发送给订单接口
      this.$router.push('/order')
    },
    showKong () {
      if (this.items.length === 0) {
        this.showCart = false
      }
    },
    deleteItem (index) {
      Dialog.confirm({
        title: '删除商品',
        message: '您确定要删除吗？'
      })
        .then(() => {
          this.items.splice(index, 1)
          this.change_num(this.items)
          this.checkedPrice()
          this.showKong()
        })
    },
    changeChecked () {
      // console.log(this.items[index].checked)
      this.change_num(this.items)
      this.checkedPrice()
      const allChecked = this.items.every(item => item.checked)
      this.change_all_checked(allChecked)
    },
    changeNum () {
      // console.log(this.items)
      this.change_num(this.items)
      this.checkedPrice()
    },
    enterDetail () {
      this.$router.push('/home')
    },
    checkedPrice () {
      // 计算已经选中的商品的价格总价格
      let sum = 0
      const checkedItems = this.items.filter((item) => item.checked)
      checkedItems.forEach((item) => {
        sum += item.minPrice * item.num
      })
      // 保留两位小数
      sum = parseFloat(sum.toFixed(2))
      // 价格变化之后，修改依赖中的值
      this.set_price(sum)
    },
    // 修改vuex中的价格依赖
    ...mapMutations('cart', ['set_price', 'change_num', 'change_all_checked', 'change_items_checked'])
  },
  computed: {
    ...mapState({
      items: (state) => JSON.parse(JSON.stringify(state.cart.items)),
      totalPrice: (state) => state.cart.totalPrice
    }),
    allChecked: {
      get () {
        return this.$store.state.cart.allChecked
      },
      set (newVal) {
        // 先根据v-model，利用计算属性的set（），来修改全选框的选中状态
        this.change_all_checked(newVal)
        // 选中框选中后，再去改变选中框状态（选中框和全选框的状态是一样的）
        this.change_items_checked(newVal)
        // 根据选中框的状态重新计算价格
        this.checkedPrice()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
/deep/.top{
  overflow: auto;
  margin-bottom: 100px;
}
.van-submit-bar {
  margin-bottom: 50px;
  border-bottom: 1px solid #ccc;
}
.top {
  padding-top: 47px;
  .van-swipe-cell__wrapper {
    position: relative;
  }
  .van-checkbox {
    position: absolute;
    top: 50px;
    left: 9px;
    z-index: 10;
  }
  .van-card {
    border-radius: 15px;
    background-color: #fff;
    margin-bottom: 8px;
  }
  /deep/.van-image__img {
    margin-left: 20px;
    margin-top: 14px;
  }
  .van-card__title {
    margin-top: 18px;
    font-size: 18px;
  }
  .van-card__content {
    margin-left: 30px;
  }
  .delete-button {
    height: 100%;
  }
}
.kongkong {
    display: flex;
    flex-direction: column;
    align-items: center;
    img {
      margin-top: 70px;
    }
    p {
      margin-top: 40px;
    }
    .guang {
      margin-top: 30px;
      width: 143px;
      outline: none;
      text-align: center;
      border-radius: 15px;
      background: red;
      color: #fff;
      font-size: 14px;
      height: 30px;
      line-height: 30px;
    }
  }
</style>
